package com.angel.controller;

import com.angel.bean.*;
import com.angel.bean.dto.SocketEmployeeDto;
import com.angel.service.*;
import com.angel.bean.*;
import com.angel.service.AppInfoService;
import com.angel.service.EmployeeTypeService;
import com.angel.service.OtherlogService;
import com.angel.shiro.SelFormAuthenticationFilter;
import com.angel.shiro.SystemAdminAuthorizingRealm;
import com.angel.service.SysMenuService;
import com.angel.socket.WebSocketUsers;
import com.angel.utils.AdminUserUtils;
import com.angel.utils.EmployeeUtils;
import com.angel.utils.LogUtils;
import com.angel.utlis.GetIpUtli;
import com.angel.utils.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 管理员登录控制器
 *
 * @author Rabit
 */
@Controller
public class LoginController {
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private OtherlogService otherlogService;

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private EmployeeTypeService employeeTypeService;

    @Autowired
    private BranchesService branchesService;

    @Autowired
    private VipInfoService vipInfoService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private BabyRecordsService babyRecordsService;

    @Autowired
    private CmsInfoService cmsInfoService;

    @Autowired
    private AppInfoService appInfoService;

    @Autowired
    private IllCaseService illCaseService;

//    /**
//     * 进入登录界面
//     *
//     * @return
//     */
//    @GetMapping("/login")
//    public String login(HttpServletRequest request) {
//        //记录登录日志
//        SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();
//        String ip = GetIpUtli.getIpAddr(request);
//
//        if (principal != null) {
//            return "index";
//        }
//        logger.info(ip + "---------------------有admin又要登录了");
//        return "login";
//    }


    @GetMapping("/upload")
    public ModelAndView userLogin() {
        //记录登录日志
        ModelAndView mv = new ModelAndView("upload");
        return mv;
    }

    /**
     * 登录成功，进入管理界面 需要用户权限
     *
     * @return
     */
    @GetMapping("/index")
    public ModelAndView adminIndex(Model model, HttpSession session) {
        SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();
        //根菜单
        List<SysMenu> menus = menuService.findMenuByEid(principal.getId());
        EmployeeType employeeType = new EmployeeType();
        employeeType.setEmTypeId(principal.getEmployee().getEmTypeId());
        employeeType = employeeTypeService.findOneType(employeeType);
        //获取当前日期
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        //获取所有分店并计算营业额;
        Branches branches = new Branches();
        List<Branches> mList = branchesService.findAll(branches);
        Double sumTurNover = 0.00;
        if(mList.size()>0){
            for (int i = 0 ; i < mList.size() ; i++){
                Branches tembranches = mList.get(i);
                if(tembranches.getReserve14()!=null){
                    sumTurNover += tembranches.getReserve14();
                }
            }
        }
        //获取所有会员并计算数量;
        List<VipInfo> vipInfoList = vipInfoService.findAll(new VipInfo());
        //员工数量
        List<Employee> employeeList = employeeService.findEmployee(new Employee());
        //宝宝档案总数
        List<BabyRecords> babyRecordsList = babyRecordsService.findAll(new BabyRecords());
        //新闻数据
        List<CmsInfo> cmsInfoList = cmsInfoService.findFiveAll(new CmsInfo());
        //等待预约人数
        IllCase illCase = new IllCase();
        if (principal.getEmployee().getEmTypeId()>2){
            illCase.setReserve15(String.valueOf(principal.getEmployee().getBranchesId()));
        }
        illCase.setIllCaseState(5);
        int state5Count = illCaseService.getIllCaseState5Count(illCase);

        int onlineCount = this.getOnlineEmp(WebSocketUsers.eMap,principal.getEmployee().getBranchesId());

        session.setAttribute("adminName", principal.getName());
        session.setAttribute("typename", employeeType.getTypeName());
        session.setAttribute("typetrust",employeeType.getTypeInstruct());
        session.setAttribute("mlist", menus);
        model.addAttribute("turnover",sumTurNover);
        model.addAttribute("dateTime",df.toString());
        model.addAttribute("vipInfoCount",vipInfoList.size());
        model.addAttribute("employeeCount",employeeList.size());
        session.setAttribute("employee",principal.getEmployee());
        //分店数量
        model.addAttribute("branchesCount",mList.size());
        model.addAttribute("babyRecordsCount",babyRecordsList.size());
        model.addAttribute("cmsInfoCount",cmsInfoList);
        model.addAttribute("state5Count",state5Count);
        model.addAttribute("onlineCount",onlineCount);
        ModelAndView mv = new ModelAndView("index", "menuModel", model);
        return mv;
    }


    /**
     * 测试vip用户登录跳转到不通页面
     *
     * @return
     */
    @GetMapping("/userindex")
    public ModelAndView userIndex() {
        ModelAndView mv = new ModelAndView("upload");
        return mv;
    }


    /**
     * 登录失败，真正登录的POST请求由Filter完成
     *
     * @param request
     * @return
     */
    @RequestMapping("login")
    public String login(HttpServletRequest request, Model model) {
        SystemAdminAuthorizingRealm.Principal principal = EmployeeUtils.getPrincipal();
        // 如果已经登录，则跳转到管理首页
        if (principal != null) {
            this.logger.info(principal.getName() + ":已经登录了");
            return "redirect:" + "/index";
        }

        String username = WebUtils.getCleanParam(request, SelFormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
        String message = (String) request.getAttribute(SelFormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);

        if (StringUtils.isBlank(message) || StringUtils.equals(message, null)) {
            message = "用户或密码错误, 请重试.";
        }
        model.addAttribute(SelFormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
        model.addAttribute(SelFormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);
        model.addAttribute("loginError", true);
        return "login";
    }

    @RequestMapping("/app")
    public String appinfoManger(Model model) {
        AppInfo appInfo = new AppInfo();
        appInfo.setId(1);
        appInfo = appInfoService.findOne(appInfo);
        model.addAttribute("app", appInfo);
        return "appinfomanager";
    }


    /**
     * 更新app首页
     */
    @RequestMapping("/updateappinfo")
    @ResponseBody
    public Map updateCmsInfo(AppInfo appInfo) {
        Map map = new HashMap();
        map.put("success",false);
        //存入当前用户id
        appInfo.setId(1);
        SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();
        appInfo.setEditor(principal.getId());
        Employee employee = principal.getEmployee();
        String msg ="更新新闻信息";
        appInfo.setState(1);
        appInfo.setRelsDate(new Timestamp(System.currentTimeMillis()));
        int result = appInfoService.update(appInfo);
        if (result != 0) {
            map.put("success",true);
            map.put("msg","app首页数据更新成功");
        } else {
           map.put("msg","app首页数据更新失败");
        }
        LogUtils.InsertLog(employee,otherlogService,msg);
        return map;
    }

    public int getOnlineEmp(Map<String, SocketEmployeeDto> eMap,int branchesId){
        Iterator iter = WebSocketUsers.eMap.entrySet().iterator();
        int count = 0;
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Employee emp = (Employee) entry.getValue();
            if(emp.getBranchesId() == branchesId){
                count++;
            }
        }
        return count;
    }



}
